package com.yj.forum.controller;

import com.yj.forum.common.AppConfig;
import com.yj.forum.common.AppResult;
import com.yj.forum.common.ResultCode;
import com.yj.forum.exception.ApplicationException;
import com.yj.forum.model.Article;
import com.yj.forum.model.Board;
import com.yj.forum.model.User;
import com.yj.forum.services.IArticleService;
import com.yj.forum.services.IBoardService;
import com.yj.forum.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(tags = "文章接口")
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IBoardService boardService;
    @ApiOperation("发新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam(value = "版块Id") @RequestParam("boardId") Long boardId,
                            @ApiParam(value = "⽂章标题") @RequestParam("title") String title,
                            @ApiParam(value = "⽂章内容") @RequestParam("content") String content) {
        //非空校验
        if(StringUtil.isEmpty(title) || StringUtil.isEmpty(content) || boardId <= 0) {
           log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
           return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Board board = boardService.selectById(boardId.longValue());
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_BANNED));
        }
        //获取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否禁言
        if(user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 构造帖⼦对象
        Article article = new Article();
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        article.setTitle(title);
        article.setContent(content);
        // 调⽤业务层
        articleService.create(article);
        // 返回结果
        return AppResult.success();

    }

    @ApiOperation("根据版块Id查询帖⼦列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("版块Id") @RequestParam(value = "boardId", required = false) Long boardId) {

        // 定义返回的集对象
        List<Article> articles = null;
        if(boardId == null) {
            articles= articleService.selectAll();
            log.info("查询所有帖⼦列表");
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }
        // 如果为null返回⼀个空JSON
        if (articles == null) {
            articles = new ArrayList<>();
        }
        // 返回结果
        return AppResult.success(articles);

    }

    /**
     * 根据Id查询帖⼦详情
     *
     * @param id 帖子Id
     * @return 指定Id的帖⼦详情
     */

    @ApiOperation("根据Id查询帖⼦详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails( HttpServletRequest request, @ApiParam("帖⼦Id") @RequestParam("id") Long id) {

        // 获取⽤⼾信息
       HttpSession session = request.getSession();
       User user = (User) session.getAttribute(AppConfig.USER_SESSION);
       // 调⽤Service层获取帖⼦详情
        Article article = articleService.selectDetailById(id);
        // 当前⽤⼾是否作者
        if(article.getUserId().equals(user.getId())) {
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    /**
     * 根据帖⼦Id更新帖⼦标题与内容
     * @param id 帖⼦Id
     * @param title 标题
     * @param content 内容
     */
    @ApiOperation("编辑帖⼦")
    @PostMapping("/modify")
    public AppResult modify( HttpServletRequest request,
                             @ApiParam("帖⼦Id") @RequestParam("id") Long id,
                             @ApiParam("⽂章标题") @RequestParam("title")String title,
                             @ApiParam("⽂章内容") @RequestParam("content")String content) {
        //获取已用户
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //判断是否禁言
        if(user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString()+", userId = " + user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //获取文章
        Article article = articleService.selectById(id);
        // 数据校验
        if(article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS);
        }
        //当前不是作者
        if(!article.getUserId().equals(user.getId())) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);

        }
        // 帖⼦状态异常
        if(article.getState() == 1 || article.getDeleteState() == 1) {
            log.warn("帖⼦状态异常.+ articleId = " + id + ", state = " +
                    article.getState() + ", delete state = " + article.getDeleteState());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS);
        }
        //调用service
        articleService.modify(id,title,content);
        // ⽇志
        log.info(MessageFormat.format("帖⼦修改成功. id = {0}, user id = {1}, 原标题 = {2}, 新标题 = {3}",
                id, user.getId(), article.getTitle(), title));
        // 返回结果
        return AppResult.success();
    }
    /**
     * 点赞
     * @param id 帖⼦Id
     */
    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @ApiParam("帖⼦Id") @RequestParam("id") Long id) {
        //非空校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //拿取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断是否禁言
        if(user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString()+ ", userId = " + user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //调用service
        articleService.thumbsUpById(id);
        return AppResult.success();
    }
    /**
     * 根据Id删除帖⼦
     *
     * @param id 帖⼦Id
     * @return
    */
    @ApiOperation("删除帖⼦")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖⼦Id")@RequestParam("id") Long id) {
        //非空校验
        if(id == null || id <= 0) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //拿用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断是否禁言
        if(user.getState() != 0) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //拿取文章
        Article article = articleService.selectById(id);
        //校验
        if(article == null || article.getState() != 0 || article.getDeleteState() != 0) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS);
        }

        //判断是不是作者
        if(!article.getUserId().equals(user.getId())) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用service
        articleService.deleteById(id);
        return AppResult.success();

    }
    /**
     * 根据⽤⼾Id查询帖⼦列表
     * @param userId ⽤⼾Id
     * @return 指定版块的帖⼦列表
     */
    @ApiOperation("根据⽤⼾Id查询帖⼦列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>>  getAllByUserId(HttpServletRequest request,
            @ApiParam("⽤⼾Id")@RequestParam(value = "userId", required = false) Long userId) {
        if(userId == null) {
            //获取用户
            HttpSession session = request.getSession();
            User user =  (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //调用service
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }

}
